package com.ck.xs.controller;

import com.ck.xs.base.BaseController;
import com.ck.xs.base.RsponseBean;
import com.ck.xs.util.DateUtil;
import com.ck.xs.util.JSONUtil;
import com.ck.xs.util.mgic.MgicTest2;
import com.ck.xs.util.mgic.MgicTest3;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 *IndexController控制
 */
@RestController
@RequestMapping("/")
public class IndexController extends BaseController {
    public static String _basePath = "";//目录
    @RequestMapping("/")
    public ModelAndView index() {
        return html("index");
    }
    @RequestMapping("/test2")
    public ModelAndView test2() {
        return html("test2/index");
    }
    @RequestMapping("/jqplayer")
    public ModelAndView jqplayer() {
        return html("jqplayer");
    }

    @RequestMapping("/videoPlay")
    public ModelAndView videoPlay(ModelMap model,String title,String videoUrl) {
        title = null == title? DateUtil.getUserDate("yyyy-MM-dd"):title;
        model.addAttribute("title", title);
        model.addAttribute("videoUrl", videoUrl);
        return html("videoPlay");
    }
    @RequestMapping("/aliplay")
    public ModelAndView aliplay() {
        return html("aliplay");
    }
    @RequestMapping("/aliplay2")
    public ModelAndView aliplay2() {
        return html("aliplay2");
    }
    @RequestMapping("/test")
    public ModelAndView test() {
        return html("test/index");
    }
    @RequestMapping("/test3")
    public ModelAndView test3() {
        return html("test3/test3");
    }


    /**
     * basePath
     * @param basePath
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/fileListLoad", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String fileListLoad(@RequestParam(required = true, value = "basePath") String basePath) {
        // 将获取的json数据封装一层，然后在给返回
        RsponseBean rsponseBean = new RsponseBean();
        if(null == basePath || basePath.equals("")){
            return JSONUtil.convertObjectToJSON(rsponseBean);
        }
        _basePath = basePath;
        List<String> list = new ArrayList<>();
        //视频所在文件目录
        try{
            File files = new File(basePath);
            if(files.exists()){
                //存在
                File[] tempList = files.listFiles();
                System.out.println(tempList.length);
                for (int i = 0; i < tempList.length; i++) {
                    if (tempList[i].isFile()) {
                        //文件名，不包含路径
                        String fileName = tempList[i].getName();
                        String _str = tempList[i].toString();
                        list.add(fileName);
                    }
                    if (tempList[i].isDirectory()) {
                        //这里就不递归了，
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        rsponseBean.setData(list);
        return JSONUtil.convertObjectToJSON(rsponseBean);
    }

    /**
     * video请求位置
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/player", method = RequestMethod.GET)
    public void player(HttpServletRequest request, HttpServletResponse response,
                       @RequestParam(required = true, value = "videoUrl") String videoUrl) {
        BufferedInputStream bis = null;
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            videoUrl = _basePath+File.separator+videoUrl;
            File file = new File(videoUrl);
            if (file.exists()) {
                long p = 0L;
                long toLength = 0L;
                long contentLength = 0L;
                int rangeSwitch = 0; // 0,从头开始的全文下载；1,从某字节开始的下载（bytes=27000-）；2,从某字节开始到某字节结束的下载（bytes=27000-39000）
                long fileLength;
                String rangBytes = "";
                fileLength = file.length();

                // get file content
                InputStream ins = new FileInputStream(file);
                bis = new BufferedInputStream(ins);

                // tell the client to allow accept-ranges
                response.reset();
                response.setHeader("Accept-Ranges", "bytes");

                // client requests a file block download start byte
                String range = request.getHeader("Range");
                if (range != null && range.trim().length() > 0 && !"null".equals(range)) {
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
                    rangBytes = range.replaceAll("bytes=", "");
                    if (rangBytes.endsWith("-")) { // bytes=270000-
                        rangeSwitch = 1;
                        p = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                        contentLength = fileLength - p; // 客户端请求的是270000之后的字节（包括bytes下标索引为270000的字节）
                    } else { // bytes=270000-320000
                        rangeSwitch = 2;
                        String temp1 = rangBytes.substring(0, rangBytes.indexOf("-"));
                        String temp2 = rangBytes.substring(rangBytes.indexOf("-") + 1, rangBytes.length());
                        p = Long.parseLong(temp1);
                        toLength = Long.parseLong(temp2);
                        contentLength = toLength - p + 1; // 客户端请求的是 270000-320000 之间的字节
                    }
                } else {
                    contentLength = fileLength;
                }

                // 如果设设置了Content-Length，则客户端会自动进行多线程下载。如果不希望支持多线程，则不要设置这个参数。
                // Content-Length: [文件的总大小] - [客户端请求的下载的文件块的开始字节]
                response.setHeader("Content-Length", new Long(contentLength).toString());

                // 断点开始
                // 响应的格式是:
                // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]
                if (rangeSwitch == 1) {
                    String contentRange = new StringBuffer("bytes ").append(new Long(p).toString()).append("-")
                            .append(new Long(fileLength - 1).toString()).append("/")
                            .append(new Long(fileLength).toString()).toString();
                    response.setHeader("Content-Range", contentRange);
                    bis.skip(p);
                } else if (rangeSwitch == 2) {
                    String contentRange = range.replace("=", " ") + "/" + new Long(fileLength).toString();
                    response.setHeader("Content-Range", contentRange);
                    bis.skip(p);
                } else {
                    String contentRange = new StringBuffer("bytes ").append("0-").append(fileLength - 1).append("/")
                            .append(fileLength).toString();
                    response.setHeader("Content-Range", contentRange);
                }

                String fileName = file.getName();
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

                int n = 0;
                long readLength = 0;
                int bsize = 1024;
                byte[] bytes = new byte[bsize];
                if (rangeSwitch == 2) {
                    // 针对 bytes=27000-39000 的请求，从27000开始写数据
                    while (readLength <= contentLength - bsize) {
                        n = bis.read(bytes);
                        readLength += n;
                        out.write(bytes, 0, n);
                    }
                    if (readLength <= contentLength) {
                        n = bis.read(bytes, 0, (int) (contentLength - readLength));
                        out.write(bytes, 0, n);
                    }
                } else {
                    while ((n = bis.read(bytes)) != -1) {
                        out.write(bytes, 0, n);
                    }
                }
            }
        } catch (IOException ie) {
            // 忽略 ClientAbortException 之类的异常
            ie.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != out){
                    out.flush();
                    out.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            try {
                if(null != bis){
                    bis.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * basePath
     * @param basePath
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/mgic", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String mgic(@RequestParam(required = true, value = "basePath") String basePath) {
        // 将获取的json数据封装一层，然后在给返回
        RsponseBean rsponseBean = new RsponseBean();
        if(null == basePath || basePath.equals("")){
            return JSONUtil.convertObjectToJSON(rsponseBean);
        }
        try{
            boolean flog = MgicTest2.mgic(basePath);
            rsponseBean.setSuccess(flog);
            rsponseBean.setMsg("成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return JSONUtil.convertObjectToJSON(rsponseBean);
    }
    /**
     * basePath
     * @param basePath
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/mgic2", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String mgic2(@RequestParam(required = true, value = "basePath") String basePath) {
        // 将获取的json数据封装一层，然后在给返回
        RsponseBean rsponseBean = new RsponseBean();
        if(null == basePath || basePath.equals("")){
            return JSONUtil.convertObjectToJSON(rsponseBean);
        }
        try{
            boolean flog = MgicTest3.mgic(basePath);
            rsponseBean.setSuccess(flog);
            rsponseBean.setMsg("成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return JSONUtil.convertObjectToJSON(rsponseBean);
    }

}
